package com.hurl.library.spider;

import java.util.ArrayList;
import java.util.List;

import com.hurl.library.util.StringUtils;

public class TemplateUrlPattern implements MultiUrlPattern {
	private String template;
	private List<UrlRule> ruleList = new ArrayList<UrlRule>();
	
	public boolean hasNext = false;
	
	public String nextUrl(){
		if(!hasNext){
			return null;
		}
		if(ruleList.isEmpty()){
			hasNext=false;
			return template;
		}else{
			String url = buildUrl(this.template,0,ruleList);
			if(url==null){
				hasNext=false;
			}
			return url;
		}
	}
	
	public String buildUrl(String template,int i,List<UrlRule> ruleList){
		if(i>ruleList.size()-1){
			return template;
		}
		if(i==ruleList.size()-1){
			String next = ruleList.get(i).next();
			if(next==null){
				return null;
			}else{
				return template.replace("{"+i+"}", next);
			}
		}
		if(i<ruleList.size()-1){
			if(ruleList.get(i+1).hasNext()){
				if(ruleList.get(i).previous()==null){
					String next = ruleList.get(i).next();
					if(next==null){
						return null;
					}else{
						return buildUrl(template.replace("{"+i+"}", next),i+1,ruleList);
					}
				}
				return buildUrl(template.replace("{"+i+"}", ruleList.get(i).previous()),i+1,ruleList);
			}else{
				String next = ruleList.get(i).next();
				if(next==null){
					return null;
				}else{
					ruleList.get(i+1).beforeFirst();
					return buildUrl(template.replace("{"+i+"}", next),i+1,ruleList);
				}
			}
		}
		return null;
	}
	public TemplateUrlPattern(String urlTemplate){
		if(StringUtils.isBlank(urlTemplate)){
			throw new ConfigurationException("指定的网址模版为空！");
		}
		this.template=urlTemplate;
		hasNext = true;
	}
	public String getUrlTemplate(){
		return template;
	}
	public void addRule(int index,UrlRule rule){
		if(index==ruleList.size()){
			ruleList.add(rule);
		}else{
			ruleList.set(index, rule);
		}
	}
	public List<UrlRule> getRuleList(){
		return ruleList;
	}
	public void getRule(int index){
		ruleList.get(index);
	}
}
